#!/usr/bin/python

import MySQLdb
import os
import string
import sys
import re
import time
import zipfile
from datetime import datetime
import numpy
import matplotlib
from pylab import *


# check if the number of arguments is correct
if(len(sys.argv) != 5):
    print "Error:\tLess than 6 arguments provided"
    print "Usage:\tdatabase_loader.py host user password database"
    print "Example:\tdatabase_loader.py localhost slamusers slamusers slamusers"
    sys.exit(0)


# params to the script for loading
host = sys.argv[1]
user = sys.argv[2]
password = sys.argv[3]
database = sys.argv[4]

# dump the info just in case
print ""
print "Database Host: %s" % host
print "Database: %s" % database
print ""
print "Waiting 1 seconds before continuing..."
time.sleep(1);

# setup the database connection we're using
conn = MySQLdb.connect (host, user, password, database)
cursor = conn.cursor ()

# the lines we're interested in comparing
lines = ('hulk','shrek', 'otg')
line2 = ('immatureT')

probes = 1

while probes <= 5:
    
    print "Plotting number of probes >= " + probes

    # create a new figure
    fig = matplotlib.pyplot.figure()
    first = fig.add_subplot(111)
    
    # perform our comparison for each line1 versus line2
    for line1 in lines:
        
        # the query we're plotting
        sql = "select (average_treat_p - avg_con_p) from bed_data where line1 = '" + line1 + "' and line2 = '" + line2 + "' and n_probes >= " + str(probes) + " order by (average_treat_p - avg_con_p)"
    
        # perform the query
        try:
            cursor.execute(sql)        
        except Exception, e:
            print e
            print "Error executing SQL Statement: " + sql
        
        # fetch the results and create scores list
        results = cursor.fetchall()
        scores = []
        for x in results:
            scores.append(x)
        
    
        first.plot(scores, label=line1)
        first.set_xlabel('Sample-Region #')
        first.set_ylabel('Change in Methylation Relative to immatureT')

        first.set_title(sql, fontsize='xx-small')
        first.grid(True)
        first.legend(loc='upper center')
        fig.savefig('MethylationDistribution-ProbeCutoff-' + str(probes) + '.pdf')
    
    
    # increment the number of probes
    probes += 1
        
        
        
        
        
        
        
        
        
        
        
        
